// src/shared/service/cartService.ts

import { CartItem, Product, ApiResponse } from '../types';
import { STORAGE_KEYS, getStorageData, setStorageData } from '../utils/storage';
import { checkAuth, getCurrentUser } from './userService';

// 生成UUID（简化版）
const generateCartItemUUID = (): string => {
  return 'cart_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
};

// ===== 购物车功能 =====

export interface CartListResponse {
  cartItems: CartItem[];
  totalQuantity: number;
  selectedQuantity: number;
  totalAmount: number;
  selectedAmount: number;
}

/**
 * 获取购物车列表
 */
export const getCart = async (): Promise<ApiResponse<CartListResponse>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const currentUser = getCurrentUser()!;

    // 获取所有购物车数据，筛选当前用户的
    const allCartItems = getStorageData<CartItem>(STORAGE_KEYS.CART_ITEMS);
    const userCartItems = allCartItems.filter(item => item.userId === currentUser.id);

    // 验证商品信息是否还存在且激活
    const products = getStorageData<Product>(STORAGE_KEYS.PRODUCTS);
    const validCartItems = userCartItems.filter(item => {
      const product = products.find(p => p.id === item.productId && p.status === 'active');
      if (product) {
        // 更新购物车中的商品信息（价格可能有变化）
        item.product = product;
        return true;
      }
      return false;
    });

    // 如果有无效的购物车项，需要清理
    if (validCartItems.length !== userCartItems.length) {
      const allValidCartItems = allCartItems.filter(item => {
        if (item.userId === currentUser.id) {
          return validCartItems.some(validItem => validItem.id === item.id);
        }
        return true; // 保留其他用户的购物车项
      });
      setStorageData(STORAGE_KEYS.CART_ITEMS, allValidCartItems);
    }

    // 计算统计信息
    const totalQuantity = validCartItems.reduce((sum, item) => sum + item.quantity, 0);
    const selectedQuantity = validCartItems
      .filter(item => item.selected)
      .reduce((sum, item) => sum + item.quantity, 0);

    const totalAmount = validCartItems.reduce((sum, item) => sum + (item.product.price * item.quantity), 0);
    const selectedAmount = validCartItems
      .filter(item => item.selected)
      .reduce((sum, item) => sum + (item.product.price * item.quantity), 0);

    return {
      code: 200,
      message: '获取购物车成功',
      data: {
        cartItems: validCartItems,
        totalQuantity,
        selectedQuantity,
        totalAmount,
        selectedAmount
      }
    };

  } catch (error) {
    console.error('获取购物车失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

export interface AddToCartRequest {
  productId: string;
  quantity: number;
}

export interface CartItemResponse {
  cartItem: CartItem;
}

/**
 * 添加商品到购物车
 */
export const addToCart = async (params: AddToCartRequest): Promise<ApiResponse<CartItemResponse>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const currentUser = getCurrentUser()!;
    const { productId, quantity } = params;

    // 参数验证
    if (!productId) {
      return {
        code: 400,
        message: '商品ID不能为空',
        data: null
      };
    }

    if (!quantity || quantity <= 0) {
      return {
        code: 400,
        message: '商品数量必须大于0',
        data: null
      };
    }

    // 验证商品是否存在且激活
    const products = getStorageData<Product>(STORAGE_KEYS.PRODUCTS);
    const product = products.find(p => p.id === productId && p.status === 'active');

    if (!product) {
      return {
        code: 404,
        message: '商品不存在或已下架',
        data: null
      };
    }

    // 检查库存
    if (product.stock < quantity) {
      return {
        code: 400,
        message: `库存不足，当前库存：${product.stock}`,
        data: null
      };
    }

    // 获取购物车数据
    const allCartItems = getStorageData<CartItem>(STORAGE_KEYS.CART_ITEMS);

    // 检查是否已在购物车中
    const existingItemIndex = allCartItems.findIndex(item =>
      item.userId === currentUser.id && item.productId === productId
    );

    let updatedCartItem: CartItem;

    if (existingItemIndex !== -1) {
      // 商品已在购物车中，增加数量
      const existingItem = allCartItems[existingItemIndex];
      const newQuantity = existingItem.quantity + quantity;

      // 检查总数量是否超过库存
      if (newQuantity > product.stock) {
        return {
          code: 400,
          message: `库存不足，当前库存：${product.stock}，购物车中已有：${existingItem.quantity}`,
          data: null
        };
      }

      updatedCartItem = {
        ...existingItem,
        quantity: newQuantity,
        product: product // 更新商品信息
      };

      allCartItems[existingItemIndex] = updatedCartItem;
    } else {
      // 新增购物车项
      updatedCartItem = {
        id: generateCartItemUUID(),
        userId: currentUser.id,
        productId: productId,
        product: product,
        quantity: quantity,
        selected: true // 默认选中
      };

      allCartItems.push(updatedCartItem);
    }

    // 保存购物车数据
    setStorageData(STORAGE_KEYS.CART_ITEMS, allCartItems);

    return {
      code: 200,
      message: '添加到购物车成功',
      data: {
        cartItem: updatedCartItem
      }
    };

  } catch (error) {
    console.error('添加购物车失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

export interface UpdateCartItemRequest {
  quantity?: number;
  selected?: boolean;
}

/**
 * 更新购物车项
 */
export const updateCartItem = async (cartItemId: string, params: UpdateCartItemRequest): Promise<ApiResponse<CartItemResponse>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const currentUser = getCurrentUser()!;
    const { quantity, selected } = params;

    // 参数验证
    if (!cartItemId) {
      return {
        code: 400,
        message: '购物车项ID不能为空',
        data: null
      };
    }

    if (quantity !== undefined && quantity <= 0) {
      return {
        code: 400,
        message: '商品数量必须大于0',
        data: null
      };
    }

    // 获取购物车数据
    const allCartItems = getStorageData<CartItem>(STORAGE_KEYS.CART_ITEMS);
    const cartItemIndex = allCartItems.findIndex(item => item.id === cartItemId);

    if (cartItemIndex === -1) {
      return {
        code: 404,
        message: '购物车项不存在',
        data: null
      };
    }

    const cartItem = allCartItems[cartItemIndex];

    // 检查是否属于当前用户
    if (cartItem.userId !== currentUser.id) {
      return {
        code: 403,
        message: '无权操作此购物车项',
        data: null
      };
    }

    // 如果更新数量，需要检查库存
    if (quantity !== undefined) {
      const products = getStorageData<Product>(STORAGE_KEYS.PRODUCTS);
      const product = products.find(p => p.id === cartItem.productId && p.status === 'active');

      if (!product) {
        return {
          code: 404,
          message: '商品不存在或已下架',
          data: null
        };
      }

      if (quantity > product.stock) {
        return {
          code: 400,
          message: `库存不足，当前库存：${product.stock}`,
          data: null
        };
      }

      // 更新商品信息
      cartItem.product = product;
    }

    // 更新购物车项
    const updatedCartItem: CartItem = {
      ...cartItem,
      quantity: quantity !== undefined ? quantity : cartItem.quantity,
      selected: selected !== undefined ? selected : cartItem.selected
    };

    allCartItems[cartItemIndex] = updatedCartItem;
    setStorageData(STORAGE_KEYS.CART_ITEMS, allCartItems);

    return {
      code: 200,
      message: '购物车更新成功',
      data: {
        cartItem: updatedCartItem
      }
    };

  } catch (error) {
    console.error('更新购物车失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

/**
 * 删除购物车项
 */
export const removeFromCart = async (cartItemId: string): Promise<ApiResponse<null>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const currentUser = getCurrentUser()!;

    // 参数验证
    if (!cartItemId) {
      return {
        code: 400,
        message: '购物车项ID不能为空',
        data: null
      };
    }

    // 获取购物车数据
    const allCartItems = getStorageData<CartItem>(STORAGE_KEYS.CART_ITEMS);
    const cartItemIndex = allCartItems.findIndex(item => item.id === cartItemId);

    if (cartItemIndex === -1) {
      return {
        code: 404,
        message: '购物车项不存在',
        data: null
      };
    }

    const cartItem = allCartItems[cartItemIndex];

    // 检查是否属于当前用户
    if (cartItem.userId !== currentUser.id) {
      return {
        code: 403,
        message: '无权操作此购物车项',
        data: null
      };
    }

    // 删除购物车项
    allCartItems.splice(cartItemIndex, 1);
    setStorageData(STORAGE_KEYS.CART_ITEMS, allCartItems);

    return {
      code: 200,
      message: '商品已从购物车中移除',
      data: null
    };

  } catch (error) {
    console.error('删除购物车项失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

/**
 * 清空购物车
 */
export const clearCart = async (): Promise<ApiResponse<null>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const currentUser = getCurrentUser()!;

    // 获取购物车数据，删除当前用户的所有项
    const allCartItems = getStorageData<CartItem>(STORAGE_KEYS.CART_ITEMS);
    const filteredCartItems = allCartItems.filter(item => item.userId !== currentUser.id);

    setStorageData(STORAGE_KEYS.CART_ITEMS, filteredCartItems);

    return {
      code: 200,
      message: '购物车已清空',
      data: null
    };

  } catch (error) {
    console.error('清空购物车失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

/**
 * 批量更新购物车项选中状态
 */
export const updateCartItemsSelected = async (cartItemIds: string[], selected: boolean): Promise<ApiResponse<null>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const currentUser = getCurrentUser()!;

    // 参数验证
    if (!cartItemIds || cartItemIds.length === 0) {
      return {
        code: 400,
        message: '购物车项ID列表不能为空',
        data: null
      };
    }

    // 获取购物车数据
    const allCartItems = getStorageData<CartItem>(STORAGE_KEYS.CART_ITEMS);
    let updatedCount = 0;

    // 批量更新选中状态
    allCartItems.forEach(item => {
      if (item.userId === currentUser.id && cartItemIds.includes(item.id)) {
        item.selected = selected;
        updatedCount++;
      }
    });

    if (updatedCount === 0) {
      return {
        code: 404,
        message: '没有找到有效的购物车项',
        data: null
      };
    }

    setStorageData(STORAGE_KEYS.CART_ITEMS, allCartItems);

    return {
      code: 200,
      message: `已更新${updatedCount}个商品的选中状态`,
      data: null
    };

  } catch (error) {
    console.error('批量更新购物车失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};